package ar.uba.fi.RSACryptoFiuba.model.encrypt;

import java.util.ArrayList;
import java.util.List;

import ar.uba.fi.RSACryptoFiuba.model.RSAAlgorithm;
import ar.uba.fi.RSACryptoFiuba.model.RSAAlgorithmStrategy;
import ar.uba.fi.RSACryptoFiuba.model.RSACalculator;
import ar.uba.fi.RSACryptoFiuba.model.RSAMessage;
import ar.uba.fi.RSACryptoFiuba.model.RSAStep;
import ar.uba.fi.RSACryptoFiuba.model.keygeneration.VoidStep;


public class RSAEncryptAlgorithm extends RSAAlgorithm{
	
	private int encryptionSteps;
		
	public RSAEncryptAlgorithm(RSAAlgorithmStrategy strategy, RSAMessage message){		
		super(strategy, message);
	}

	@Override
	public void init() {
		
		RSAStep generateNumericalRepresentationStep = new GenerateNumericalRepresentationStep();
		
		RSAEncryptMessage encryptMessage = ((RSAEncryptMessage)this.getMessage());
		double l = encryptMessage.getNKey().length();
		
		double mLenght = RSACalculator.getASCIIRepresentation(encryptMessage.getPlainText()).toString().length();
		int chunks = (int) Math.ceil(mLenght / (l-1));
		List<RSAStep> encryptSteps = new ArrayList<RSAStep>();
		for (int i = 0; i < chunks; i++) {
			encryptSteps.add(new EncryptStep(i));
		}
		
		generateNumericalRepresentationStep.setNext(encryptSteps.get(0));
		for (int i = 0; i < chunks - 1; i++) {
			encryptSteps.get(i).setNext(encryptSteps.get(i+1));
		}
		
		encryptSteps.get(0).setPrevious(generateNumericalRepresentationStep);
		for (int i = chunks-1; i > 0; i--) {
			encryptSteps.get(i).setPrevious(encryptSteps.get(i-1));
		}
		
		RSAStep resultsStep = new VoidStep();
		resultsStep.setPrevious(encryptSteps.get(chunks-1));
		encryptSteps.get(chunks-1).setNext(resultsStep);
		
		this.setCurrentStep(generateNumericalRepresentationStep);
		this.encryptionSteps = chunks;
	}

	public int getEncryptionSteps() {
		return encryptionSteps;
	}

}
